package team.scau.laboratory_repair.common.utils;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.ComparableExpressionBase;
import lombok.NonNull;
import lombok.extern.apachecommons.CommonsLog;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * @author 30254
 * creadtedate:2018/8/20
 */
@CommonsLog
public class QDSLTool {

    public static OrderSpecifier[] warpSort(Class<?> clazz, LinkedHashMap<String, Order> sortMap) {
        Set<Map.Entry<String, Order>> entrySet = sortMap.entrySet();
        OrderSpecifier[] orders = new OrderSpecifier[entrySet.size()];
        Iterator<Map.Entry<String, Order>> iterator = entrySet.iterator();
        int i = 0;
        while (iterator.hasNext()) {
            Map.Entry<String, Order> next = iterator.next();
            orders[i++] = new OrderSpecifier<>(next.getValue(), getQBeanColumn(clazz, next.getKey()));
        }
        return orders;
    }

    @SuppressWarnings("unchecked")
    public static ComparableExpressionBase<Comparable> getQBeanColumn(@NonNull Class<?> clazz, @NonNull String column) {
        try {
            Field[] fields = clazz.getFields();
            Object qType = null;
            for (Field f : fields) {
                int flag = f.getModifiers();
                if (Modifier.isStatic(flag) && Modifier.isFinal(flag) && clazz.equals(f.getType())) {
                    qType = f.get(clazz);
                    break;
                }
            }
            ComparableExpressionBase<Comparable> path = null;
            Field field = clazz.getField(column);
            Class<?> classes = field.getType().getSuperclass();
            while (classes != Object.class) {
                if (classes.equals(ComparableExpressionBase.class)) {
                    path = (ComparableExpressionBase<Comparable>) field.get(qType);
                    break;
                }
                classes = classes.getSuperclass();
            }
            return path;
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
        return null;
    }
}
